import _ from 'lodash-es'
import { objectMergLeft } from '@/utils/common'
/**
 * apis add\edit\del\info
 */
const ACTIONS = {
  view: '查看',
  edit: '修改',
  add: '添加',
  del: '删除',
}
export const useCrudPro = ({
  name = '',
  title = '',
  initForm = {},
  apis = {},
  handleChange,
  handleReset,
  onShow,
  onReady,
  formatParams,
}) => {
  //表单数据
  const model = ref(_.cloneDeep(initForm))
  //表单ref
  const $form = ref(null)
  //数据表格ref
  const $table = ref(null)
  // 表单操作类型 add|edit|view
  const type = ref('')
  //表单是否数据渲染完成
  const isRender = ref(false)
  async function showForm(actionType, data = {}, callBack = () => {}) {
    isRender.value = false
    type.value = actionType
    $form.value.setState('title', title || `${ACTIONS[type.value]}${name}`)
    $form.value.setState('showFlag', true)
    if (typeof onShow === 'function') {
      onShow(type.value)
    }
    if (typeof callBack === 'function') {
      callBack()
    }
    model.value = _.cloneDeep(initForm)
    if (type.value !== 'add') {
      if (typeof apis.info === 'function') {
        // 异步初始化
        $form.value.setState('loadingFlag', true)
        const result = await apis.info(_.cloneDeep(data))
        model.value = objectMergLeft(model.value, _.cloneDeep(result))
        nextTick(() => {
          $form.value.setState('loadingFlag', false)
        })
      } else {
        // 同步初始化
        model.value = objectMergLeft(model.value, data)
      }
    }
    isRender.value = true
    if (typeof onReady === 'function') {
      onReady(type.value)
    }
  }
  function handleAdd(callBack) {
    showForm('add', null, callBack)
  }
  function handleEdit(data, callBack) {
    showForm('edit', data, callBack)
  }
  function handleView(data, callBack) {
    showForm('view', data, callBack)
  }
  async function handleSubmit(params) {
    if (!['add', 'edit'].includes(type.value)) return
    let p = params
    if (typeof formatParams === 'function') {
      p = await formatParams(_.cloneDeep(params))
    }
    $form.value.setState('submitFlag', true)
    apis[type.value](p)
      .then((res) => {
        $form.value.setState('submitFlag', false)
        $form.value.setState('showFlag', false)
        onChange(type.value, res)
      })
      .catch((err) => {
        console.log('err:', err)
        $form.value.setState('submitFlag', false)
      })
  }

  function handleDelete(data, options = {}) {
    const dialog = $dialog.warning({
      title: '提示',
      content: '确定删除？',
      negativeText: '取消',
      positiveText: '确定',
      positiveButtonProps: {
        color: '#0A56D8FF',
      },
      async onPositiveClick() {
        try {
          dialog.loading = true
          const res = await apis.del(data)
          dialog.loading = false
          onChange('del', res)
        } catch (error) {
          console.log('error:', error)
          dialog.loading = false
        }
      },
      ...options,
    })
  }
  function onChange(actionType, res) {
    if (typeof handleChange === 'function') {
      handleChange(actionType, res, model)
    } else {
      $message.success(`${ACTIONS[actionType]}${name}成功!`)
      if (actionType !== 'add') {
        $table?.value?.handleQuery()
      } else {
        $table?.value?.handleSearch()
      }
      if (typeof handleReset === 'function') {
        handleReset(type.value)
      }
    }
  }
  return {
    type,
    model,
    isRender,
    $form,
    $table,
    handleAdd,
    handleEdit,
    handleView,
    handleSubmit,
    handleDelete,
  }
}
